import { useSelector, useDispatch } from 'react-redux'
import styles from "./index.module.scss"
import { Button, Form, Input, Select, Upload, message } from "antd"
import type { GetProp, UploadProps } from 'antd';
import { LoadingOutlined, PlusOutlined } from "@ant-design/icons"
import { useState, useEffect } from "react"
import { User_up_avatar } from "@/apis/user"
import { Editor, Toolbar } from '@wangeditor/editor-for-react'
import { IDomEditor, IToolbarConfig, IButtonMenu, Boot } from '@wangeditor/editor'
import '@wangeditor/editor/dist/css/style.css'
import { Local } from '@/utils/local';
import { setCatalog } from "@/store/FoodStore/FoodStore"
import { useSearchParams } from 'react-router-dom';
import { Get_One, PutFood, ADD_Food } from "@/apis/foods"
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import { foodquar } from "@/apis/admin/echar"
const base_url = import.meta.env.VITE_APP_URL
const normFile = (e: any) => {
    if (Array.isArray(e)) {
        return e;
    }
    return e?.fileList;
};
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
const beforeUpload = (file: FileType) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' || file.type === 'image/webp';
    if (!isJpgOrPng) {
        message.error('只能上传jpg,png,gif,webp');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('最大2MB!');
    }
    return isJpgOrPng && isLt2M;
};
const Edit_Food = () => {
    let timer: any = null;
    const [form] = Form.useForm()
    const navigate = useNavigate()
    const [params] = useSearchParams()
    const dispatch = useDispatch()
    const [imageUrl, setImageUrl] = useState<string>();
    const [tempurl, settempurl] = useState<string>('/deliciousimg/default/780.jpg')
    const [loading, setLoading] = useState(false);
    const [isEdit, setisEdit] = useState(false)
    const catalog = useSelector((state: any) => state.FoodStore.catalog)
    const thems = useSelector((state: any) => state.Appstore.theme)
    const [articid, setarticid] = useState('')
    //富文本区域--------------------start---------------------------------------
    const [editor, setEditor] = useState<IDomEditor | null>(null)
    const [html, setHtml] = useState('')
    //-------------目录--------------------
    class MyButtonMenu implements IButtonMenu {
        public title
        public tag
        constructor() {
            this.title = '生成目录'

            this.tag = 'button'
        }

        getValue(_: IDomEditor): string | boolean {
            return ''
        }

        isActive(_: IDomEditor): boolean {
            return false
        }


        isDisabled(_: IDomEditor): boolean {
            return false
        }

        // 点击菜单时触发的函数
        exec(editor: IDomEditor, _: string | boolean) {   // TS 语法
            if (this.isDisabled(editor)) return

            const headers = editor.getElemsByTypePrefix('header')
            const nodeenum: object[] = []
            let nodes = headers.filter((item: any) => item.type === 'header1' || item.type == "header2").map((item: any) => {
                nodeenum.push(item)
                let node: any = {
                    type: 'paragraph',
                    children: [{
                        text: item.children[0].text,
                        color: 'rgb(103, 149, 181)'
                    }],
                }
                if (item.type === 'header1') {
                    node.indent = '2em'

                }

                if (item.type === 'header2') {
                    node.indent = '4em'

                }
                return node
            })
            //生成
            dispatch(setCatalog(nodeenum))

        }

    }
    const menu1Conf = {
        key: 'catalog', // 定义 menu key ：要保证唯一、不重复（重要）
        factory() {
            return new MyButtonMenu() // 把 `YourMenuClass` 替换为你菜单的 class
        },
    }



    //------------目录--------------------

    // 工具栏配置
    const toolbarConfig: Partial<IToolbarConfig> = {}

    // 编辑器配置
    const editorConfig = {
        MENU_CONF: {
            "uploadImage": {}
        }
    }
    //上传图片-----------------------------
    editorConfig.MENU_CONF['uploadImage'] = {
        timeout: 5 * 1000,
        //默认
        fieldName: 'wangeditor-uploaded-image',
        //图片大小限制
        maxFileSize: 10 * 1024 * 1024, // 10M

        base64LimitSize: 5 * 1024, // 5kb 以下插入 base64

        onBeforeUpload(files: any) {
            console.log('onBeforeUpload', files)

            return files // 返回哪些文件可以上传
            // return false 会阻止上传
        },
        async customUpload(file: any, insertFn: any) {                   // JS 语法
            /* file 即选中的文件
            */
            const newsform = new FormData()
            newsform.append("file", file)

            const result = await axios.post(`${base_url}/upload/user`, newsform, {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            })
            console.log(result, 'dasdsa')
            const url = base_url + result.data.path
            // 最后插入图片
            insertFn(url)
        },
        onProgress(progress: any) {
            console.log('onProgress', progress)
        },
        onSuccess(file: any, res: any) {
            console.log('onSuccess', file, res)
        },
        onFailed(file: any, res: any) {
            alert(res.message)
            console.log('onFailed', file, res)
        },
        onError(file: any, err: any, res: any) {
            alert(err.message)
            console.error('onError', file, err, res)
        },

    }

    //上传图片---------------------------


    toolbarConfig.insertKeys = {
        index: 33, // 插入的位置，基于当前的 toolbarKeys
        keys: ['catalog', 'header1', 'header2']
    }
    toolbarConfig.excludeKeys = [
        'group-video',
        'codeBlock',
        'fullScreen',
    ]
    useEffect(() => {
        if (editor?.getAllMenuKeys()?.length === 60) {
            Boot.registerMenu(menu1Conf);
        }
        timer = setTimeout(async () => {
            if (params.get('id')) {
                clearTimeout(timer)
                const res = await Get_One(params.get('id') as string)
                setisEdit(true)
                setHtml(res.data.rich_text2)
                setImageUrl(base_url + res.data.Cover_img)
                settempurl(res.data.Cover_img)
                setarticid(res.data._id)
                form.setFieldsValue({
                    title: res.data.title,
                    type: res.data.type
                })
                dispatch(setCatalog(res.data.catalog))
            }
        }, 0);

        return () => {
            if (editor == null) return
            editor.destroy()
            setEditor(null)
            dispatch(setCatalog([]))
        }
    }, [editor])
    //富文本区域----------------end---------------------------------------
    const onFinish = async (e: any) => {
        const userinfo = Local.get_info()
        const texttual = editor?.getText()
        const htmls = editor?.getHtml()
        const edits = document.querySelector('.w-e-scroll')
        const HeaderAll = edits?.querySelectorAll('h1,h2')
        HeaderAll?.forEach((item: any, index: number) => {
            if (catalog.length === 0) return
            item.setAttribute("id", catalog[index].children[0].text)
        })
        const value = { ...e, type: e.type[0], user_id: userinfo._id, Cover_img: tempurl, rich_text: edits?.innerHTML, rich_text2: htmls, texttual, catalog: catalog, publish_time: Date.now() }
        if (isEdit) {
            const res = await PutFood(articid, value)
            if (res.status == 200) {
                message.success("修改成功")
                dispatch(setCatalog([]))
                navigate('/user')
            }
        } else {
            const res = await ADD_Food(value)
            foodquar(e.type[0])
            if (res.status == 200) {
                message.success("添加成功")
                dispatch(setCatalog([]))
                navigate('/user')
            }
        }

    }
    const onFinishFailed = () => {
    }
    //上传图片
    const myup = async (e: any) => {
        setLoading(true)
        const formData = new FormData();
        formData.append('file', e.file)
        const res: any = await User_up_avatar(formData)

        if (res.code === 200) {
            settempurl(res.path)
            setLoading(false)
            setImageUrl(base_url + res.path)
        }
    }
    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>{loading ? '上传中' : '上传'}</div>
        </button>
    );

    return (
        <div className={styles.food}>
            <div className={thems ? styles.foodbody2 : styles.foodbody} style={{
                height: "90vh", overflowY: "scroll",
                width: "70%", background: thems ? 'rgba(255,255,255,0.7)' : 'rgba(0,0,0,0.4)', marginTop: "10px", padding: "10px"
            }}>

                <Form
                    form={form}
                    name="basic"

                    style={{ maxWidth: 900 }}
                    initialValues={{ remember: true }}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                >
                    <Form.Item
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 10 }}
                        label="文章标题"
                        name="title"
                        rules={[{ required: true, message: '长度在2-10', max: 10, min: 2 }]}
                    >
                        <Input placeholder='标题' />
                    </Form.Item>
                    <Form.Item
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 5 }}
                        label="分类"
                        name="type"
                        initialValue={['0']}
                        rules={[{ required: true, message: '必填' }]}
                    >
                        <Select options={[{ value: '0', label: "主菜" }, { value: '1', label: "汤品" }, { value: "2", label: "甜品/烘焙" }, { value: '3', label: "饮料" }]} />
                    </Form.Item>
                    <Form.Item
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 5 }}
                        label="封面"
                        valuePropName="fileList"
                        name="cover_img"
                        getValueFromEvent={normFile}
                    >

                        <Upload
                            name="file"
                            listType="picture-card"
                            className={styles.uploader}
                            showUploadList={false}
                            customRequest={myup}
                            beforeUpload={beforeUpload}

                        >
                            {imageUrl ? <img src={imageUrl} alt="cover_img" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 19 }}
                        label="目录">

                        {
                            catalog.length !== 0 ?

                                catalog.map((item: any, index: number) => {
                                    return <p key={index} style={{ marginLeft: item.type === "header2" ? '10px' : '', color: item.type === "header2" ? "rgb(103, 149, 181)" : "" }}>{item.children[0].text}</p>
                                })
                                : ''
                        }
                    </Form.Item>
                    <Form.Item labelCol={{ span: 5 }}
                        wrapperCol={{ span: 19 }}
                        label="内容">


                        <Toolbar
                            editor={editor}
                            defaultConfig={toolbarConfig}
                            mode="small"
                            className={styles.htmldarktool}
                            style={{ sizeCalculable: "10px", borderBottom: '1px solid #ccc' }}
                        />
                        <Editor
                            className={styles.htmldarktext}
                            defaultConfig={editorConfig}
                            value={html}
                            onCreated={setEditor}
                            onChange={editor => setHtml(editor.getHtml())}
                            mode="default"
                            style={{ height: '400px', overflowY: 'hidden' }}
                        />

                    </Form.Item>
                    <Form.Item label="提交" labelCol={{ span: 5 }} wrapperCol={{ span: 16 }}>

                        <Button htmlType="submit" type="primary">提交</Button>
                    </Form.Item>
                </Form>

            </div>

        </div>
    )
}

export default Edit_Food